import { LOGIN, LOGOUT, SET_USER_INFO } from 'Constants/userConstants';
import Cookies from 'js-cookie';

const initialState = {
  id: Cookies.get('id') || 0,
  name: Cookies.get('name') || '',
  isLogin: Cookies.get('_isLogin') === 'true',
  testID: Cookies.get('testID') || '',
};

export default function userReducer(state = initialState, action) {
  switch (action.type) {
    case LOGIN:
      Cookies.set('id', action.userInfo.id);
      Cookies.set('name', action.userInfo.name);
      Cookies.set('_isLogin', 'true');
      Cookies.set('testID', action.userInfo.testID);
      return Object.assign({}, state, {
        isLogin: true,
        ...action.userInfo,
      });
    case LOGOUT:
      Cookies.remove('id');
      Cookies.remove('_isLogin');
      Cookies.remove('name');
      Cookies.remove('testID');
      return Object.assign({}, initialState, {
        isLogin: false,
      });
    case SET_USER_INFO:
      return Object.assign({}, state, {
        ...action.userInfo
      });
    default:
      return state;
  }
}
